package modules.fin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.util.ValidatorUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import luxing.web.model.SortDirection;
import modules.fin.entity.Expenses;
import modules.fin.entity.Income;
import modules.fin.entity.IncomeUnit;
import modules.fin.entity.Outlay;
import modules.fin.service.ExpensesService;
import modules.fin.service.IncomeService;
import modules.fin.service.IncomeUnitService;
import modules.fin.service.OutlayService;
import modules.sys.entity.Log;
import modules.sys.service.LogService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/expensesController")
public class ExpensesController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ExpensesController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private ExpensesService expensesService;
	@Autowired
	private IncomeService incomeService;
	@Autowired
	private IncomeUnitService incomeUnitService;
	@Autowired
	private OutlayService outlayService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		return new ModelAndView("modules/fin/expenses-list");
	}

	/**
	 * 列表数据
	 * 
	 * @param expenses
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(Expenses expenses, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Expenses.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, expenses, request.getParameterMap());
			cq.addOrder("type", SortDirection.asc);
			cq.add();
			expensesService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("费用类型查询失败", e);
			throw new BusinessException("费用类型查询失败", e);
		}
	}

	/**
	 * 新增页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		return new ModelAndView("modules/fin/expenses-add");
	}

	/**
	 * 修改页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(Expenses expenses, HttpServletRequest req) {
		if (StringUtils.isNotBlank(expenses.getId())) {
			expenses = expensesService.get(Expenses.class, expenses.getId());
			req.setAttribute("expensesPage", expenses);
		}
		return new ModelAndView("modules/fin/expenses-update");
	}

	/**
	 * 增加
	 * 
	 * @param expenses
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public Result doAdd(Expenses expenses, HttpServletRequest request) {
		String msg = null;
		try {
			expenses.setStatus(Expenses.STATUS_ENABLE);
			// bean校验
			msg = ValidatorUtil.validate(expenses);
			if (StringUtils.isNotBlank(msg)) {
				return Result.error(msg);
			}
			expensesService.save(expenses);
			msg = "费用类型\"" + expenses.getName() + "\"增加成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_ADD);
		} catch (Exception e) {
			msg = "费用类型\"" + expenses.getName() + "\"增加失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 修改
	 * 
	 * @param expenses
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public Result doUpdate(Expenses expenses, HttpServletRequest request) {
		String msg = null;
		try {
			expensesService.saveOrUpdate(expenses);
			msg = "费用类型\"" + expenses.getName() + "\"修改成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "费用类型\"" + expenses.getName() + "\"修改失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public Result doDel(Expenses expenses, HttpServletRequest request) {
		String msg = null;
		try {
			expenses = expensesService.get(Expenses.class, expenses.getId());
			if (StringUtils.equals(expenses.getType(), Expenses.TYPE_INCOME)) {
				// 收车辆款
				List<Income> incomeList = incomeService.listByExpenses(expenses.getId());
				if (CollectionUtils.isNotEmpty(incomeList)) {
					msg = "费用类型\"" + expenses.getName() + "\"已经使用,无法删除";
					return Result.error(msg);
				}
			}
			if (StringUtils.equals(expenses.getType(), Expenses.TYPE_OUTLAY)) {
				// 付车辆款
				List<Outlay> outlayList = outlayService.listByExpenses(expenses.getId());
				if (CollectionUtils.isNotEmpty(outlayList)) {
					msg = "费用类型\"" + expenses.getName() + "\"已经使用,无法删除";
					return Result.error(msg);
				}
			}
			if (StringUtils.equals(expenses.getType(), Expenses.TYPE_INCOME_UNIT)) {
				// 收单位款
				List<IncomeUnit> incomeUnitList = incomeUnitService.listByExpenses(expenses.getId());
				if (CollectionUtils.isNotEmpty(incomeUnitList)) {
					msg = "费用类型\"" + expenses.getName() + "\"已经使用,无法删除";
					return Result.error(msg);
				}
			}
			if (StringUtils.equals(expenses.getType(), Expenses.TYPE_OUTLAY_UNIT)) {
				// 付单位款
				// TODO
			}

			expensesService.delete(expenses);
			msg = "费用类型\"" + expenses.getName() + "\"删除成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_DEL);
		} catch (Exception e) {
			msg = "费用类型\"" + expenses.getName() + "\"删除失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

}
